package com.efast.dmom.mgmt.service.mes.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.dmom.mgmt.bean.mes.InfPpPlan;
import com.efast.dmom.mgmt.bean.mes.TwProductionSplitDto;
import com.efast.dmom.mgmt.bean.mes.order.WorkOrderItem;
import com.efast.dmom.mgmt.dao.mes.TwProductionPlanMapper;
import com.efast.dmom.mgmt.entity.mes.TwBasWorkOrder;
import com.efast.dmom.mgmt.entity.mes.TwPlanSplit;
import com.efast.dmom.mgmt.entity.mes.TwProductionPlan;
import com.efast.dmom.mgmt.service.mes.TwBasWorkOrderService;
import com.efast.dmom.mgmt.service.mes.TwProductionPlanService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ChenLiPeng
 * @since 2018-06-20
 */
@Transactional
@Service
public class TwProductionPlanServiceImpl extends ServiceImpl<TwProductionPlanMapper, TwProductionPlan>
		implements TwProductionPlanService {

	private static final String String = null;
	@Autowired
	private TwProductionPlanMapper twProductionPlanMapper;
	@Autowired
	private TwBasWorkOrderService twBasWorkOrderService;
	@Qualifier("jdbcDao")
	@Autowired
	private JdbcDao jdbcDao;
	
	private final String ORDER_ITEM_SUFFIX = "-";
	private final String ORDER_ITEM_SUFFIX_00 = ORDER_ITEM_SUFFIX + "00";
	private final String ORDER_ITEM_SUFFIX_0 = ORDER_ITEM_SUFFIX + "0";
	

	@Override
	public void planColsed(TwProductionPlan twProductionPlan) {
		twProductionPlan.setStatus("closed");
		twProductionPlanMapper.updateById(twProductionPlan);
	}
	

	@Override
	public void planWorkSplitOrder(Map<java.lang.String, Object> map, Integer splitQty, Integer singerOrderQty) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); 
		@SuppressWarnings("unchecked")
		List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("params");
		Map<Object, Object> hashMap = new HashMap<Object, Object>();
		TwBasWorkOrder twBasWorkOrder = new TwBasWorkOrder();
		twBasWorkOrder.setOrderType("NORMAL");
		twBasWorkOrder.setSource("MANUAL");
		twBasWorkOrder.setStatus("CREATED");
		twBasWorkOrder.setMarkStatus(0);
		for(int i=0;i<list.size();i++) {
			Map<String, Object> map2 = list.get(i);
			Integer id = (Integer)map2.get("id");
			Integer qty = (Integer)map2.get("qty");
			twBasWorkOrder.setPartNo((String)map2.get("poPartNo"));
			twBasWorkOrder.setPartNoVersion((String)map2.get("poPartNoVersion"));
			twBasWorkOrder.setLineId((Integer)map2.get("lineId"));
			twBasWorkOrder.setLineName((String)map2.get("lineName"));
			twBasWorkOrder.setPlanId(id);
			twBasWorkOrder.setPlanOrder((String)map2.get("planOrderNo"));
			twBasWorkOrder.setCreateUser(SpringWebUtils.getRequestUser());
			twBasWorkOrder.setLastUpdateTime(new Date());
			twBasWorkOrder.setLastUpdateUser(SpringWebUtils.getRequestUser());
//			twBasWorkOrder.setSto((String)map2.get("sto"));
			
			try {
				if(map2.get("planOnlineDate")!=null||map2.get("planOnlineDate")!="") {
					twBasWorkOrder.setPlanStartTime(format1.parse((String)map2.get("planOnlineDate")));
				}
				if(map2.get("planOfflineDate")!=null||map2.get("planOfflineDate")!="") {
					twBasWorkOrder.setPlanFinishTime(format1.parse((String)map2.get("planOfflineDate")));
				}
			} catch (ParseException e) {
				throw new ServiceException("无法生成工单请检查数据！");
			}
			twBasWorkOrder.setSalesOrder((String)map2.get("planOrderNo"));
			Integer total = splitQty*singerOrderQty;
			if (total > qty) {
				throw new ServiceException("填写数量已经超过总数量，请检查填写数据！");
			} else {
				if (total == qty) {
					twBasWorkOrder.setOrderedQty(Double.valueOf(singerOrderQty));
					for(int x=0;x<splitQty;x++) {
						twBasWorkOrderService.insertTwBasWorkOrder(twBasWorkOrder);
					}
				} else {
					twBasWorkOrder.setOrderedQty(Double.valueOf(singerOrderQty));
					for(int x=0;x<splitQty;x++) {
						twBasWorkOrderService.insertTwBasWorkOrder(twBasWorkOrder);
					}
					twBasWorkOrder.setOrderedQty(Double.valueOf(qty-total));
					twBasWorkOrderService.insertTwBasWorkOrder(twBasWorkOrder);
				}
			}
			
		}
		
	}

	@SuppressWarnings({ "deprecation", "static-access" })
	@Override
	public ResultBean planWorkOrder(Map<String, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); 
		@SuppressWarnings("unchecked")
		List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("params");
		for (Map<String, Object> ppInf : list) {
			String poPartNoVersion = (String)ppInf.get("poPartNoVersion");
			Integer selectTrBasPdPlRouteByPartNoVersion = twProductionPlanMapper.selectTrBasPdPlRouteByPartNoVersion(poPartNoVersion);
			if (selectTrBasPdPlRouteByPartNoVersion == null || selectTrBasPdPlRouteByPartNoVersion == 0) {
				result.setSuccess(false);
				result.setMessage("物料/"+poPartNoVersion+"/没有配置产品定义！");
				return result;
			}
			Integer selectPmLoadingListHeadByPartNoVersion = twProductionPlanMapper.selectPmLoadingListHeadByPartNoVersion(poPartNoVersion);
			if (selectPmLoadingListHeadByPartNoVersion == null || selectPmLoadingListHeadByPartNoVersion == 0) {
				result.setSuccess(false);
				result.setMessage("物料/"+poPartNoVersion+"/没有配置装车单！");
				return result;
			}
			Integer selectTmBasBomByPartNoVersion = twProductionPlanMapper.selectTmBasBomByPartNoVersion(poPartNoVersion);
			if (selectTmBasBomByPartNoVersion == null || selectTmBasBomByPartNoVersion == 0) {
				result.setSuccess(false);
				result.setMessage("物料/"+poPartNoVersion+"/没有配置BOM！");
				return result;
			}
		}
		for(int i=0;i<list.size();i++) {
			Map<String, Object> map2 = list.get(i);
			Integer planId = (Integer)map2.get("id");
			Integer qty = (Integer)map2.get("qty");
			
			TwBasWorkOrder twBasWorkOrder = new TwBasWorkOrder();
			twBasWorkOrder.setOrderType("NORMAL");
			twBasWorkOrder.setSource("MANUAL");
			twBasWorkOrder.setStatus("CREATED");
			twBasWorkOrder.setMarkStatus(0);
			
			twBasWorkOrder.setOrderedQty(Double.valueOf(qty));
			twBasWorkOrder.setPartNo((String)map2.get("poPartNo"));
			twBasWorkOrder.setPartNoVersion((String)map2.get("poPartNoVersion"));
			twBasWorkOrder.setLineId((Integer)map2.get("lineId"));
			twBasWorkOrder.setLineName((String)map2.get("lineName"));
			twBasWorkOrder.setPlanId(planId);
			twBasWorkOrder.setPlanOrder((String)map2.get("planOrderNo"));
			twBasWorkOrder.setVehicleModel((String)map2.get("flagVin"));
			twBasWorkOrder.setCreateUser(SpringWebUtils.getRequestUser());
			twBasWorkOrder.setLastUpdateTime(new Date());
			twBasWorkOrder.setLastUpdateUser(SpringWebUtils.getRequestUser());
			
			try {
				if(map2.get("planOnlineDate")!=null||map2.get("planOnlineDate")!="") {
					twBasWorkOrder.setPlanStartTime(format1.parse((String)map2.get("planOnlineDate")));
				}
				if(map2.get("planOfflineDate")!=null||map2.get("planOfflineDate")!="") {
					twBasWorkOrder.setPlanFinishTime(format1.parse((String)map2.get("planOfflineDate")));
				}
			} catch (ParseException e) {
				throw new ServiceException("无法生成工单请检查数据！");
			}
			twBasWorkOrder.setSalesOrder((String)map2.get("planOrderNo"));
			twBasWorkOrderService.insertTwBasWorkOrder(twBasWorkOrder);
			
			
			int capacityCounter = 0;
			Map<Date, Integer> capacityMap = twBasWorkOrderService.getCapacityInfo(planId);
			Date dateCounter = twBasWorkOrder.getPlanStartTime();
				
			List<WorkOrderItem> itemList = new ArrayList<WorkOrderItem>();
			//Aaron: create workorder item
				for(int j=0; j<qty; j++){
					
					capacityCounter = capacityCounter + 1;
					
					WorkOrderItem orderItem = new WorkOrderItem();
					orderItem.setOrderKey(twBasWorkOrder.getOrderId());
					orderItem.setOrderNumber(twBasWorkOrder.getOrderNumber());
					orderItem.setOrderStatus(twBasWorkOrder.getStatus());
					orderItem.setPartNoVersion(twBasWorkOrder.getPartNoVersion());
					orderItem.setPartNumber(twBasWorkOrder.getPartNo());
					orderItem.setPlanEndTime(twBasWorkOrder.getPlanFinishTime());
						
					Integer scheduledQty = capacityMap.get(dateCounter);
					if(scheduledQty != null && scheduledQty < capacityCounter){
						dateCounter.setDate(dateCounter.getDate() + 1);
						capacityCounter = 0;
					}
					
					Date startDate = new Date();
					startDate.setDate(dateCounter.getDate());
					orderItem.setPlanStartTime(startDate);
					
					orderItem.setVehicleModel(twBasWorkOrder.getVehicleModel());
					
					if((j+1) <= 9){
						orderItem.setOrderItemName(twBasWorkOrder.getOrderNumber() + ORDER_ITEM_SUFFIX_00 + (j + 1));
					}else if((j+1) > 9){
						orderItem.setOrderItemName(twBasWorkOrder.getOrderNumber() + ORDER_ITEM_SUFFIX_0 + (j + 1));
					}else{
						orderItem.setOrderItemName(twBasWorkOrder.getOrderNumber() + ORDER_ITEM_SUFFIX + (j + 1));
					}
					
					//TODO
					String tmp = jdbcDao.executeProcGetCode("order_item_sequence", "CJQC");
					
					StringBuffer sequence = new StringBuffer();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
					String currentDate = dateFormat.format(new Date()).substring(8);
					sequence.append(String.valueOf(startDate.getYear()+1900)).append(String.valueOf(startDate.getMonth()+1)).append(String.valueOf(startDate.getDate())).append(currentDate);
					
					orderItem.setSequence(sequence.append(tmp.substring(tmp.length()-4, tmp.length())).toString());
					sequence.delete(0, sequence.length());
					sequence = null;
					
					orderItem.setCreateTime(new Date());
					orderItem.setCreateUser(SpringWebUtils.getRequestUser());
					orderItem.setLastUpdateTime(new Date());
					orderItem.setLastUpdateUser(SpringWebUtils.getRequestUser());
					
					itemList.add(orderItem);
				}
				
				//Aaron : save workorder items
		        twBasWorkOrderService.insertWorkItem(itemList);
		        
		        twProductionPlanMapper.updateInfPpPlanById(planId);
		}
		
		return result;
	}

	@Override
	public void planMakeWorkOrder(TwPlanSplit twPlanSplit) {
		TwBasWorkOrder twBasWorkOrder = new TwBasWorkOrder();
		TwProductionSplitDto twProductionSplitDto = twProductionPlanMapper
				.selectByTwPlanSplitId(twPlanSplit.getTwPlanSplitId());
		twBasWorkOrder.setOrderType("NORMAL");
		if (twProductionSplitDto.getPlanQuantity() != null) {
			twBasWorkOrder.setFinishedQty(Double.parseDouble(String.valueOf(twProductionSplitDto.getPlanQuantity())));
		}
		twBasWorkOrder.setPartNo(twProductionSplitDto.getProductNo());
		twBasWorkOrder.setSource("MANUAL");
		twBasWorkOrder.setPriority(String.valueOf(twProductionSplitDto.getPriority()));
		twBasWorkOrder.setPlanStartTime(twProductionSplitDto.getPlanBeginTime());
		twBasWorkOrder.setPlanFinishTime(twProductionSplitDto.getPlanEndTime());
		twBasWorkOrder.setSalesOrder(twProductionSplitDto.getSalesOrder());
		twBasWorkOrder.setCustomer(twProductionSplitDto.getCustomerName());
		String ASNcode = jdbcDao.executeProcGetCode("tw_bas_work_order", "efast");
		twBasWorkOrder.setOrderNumber(ASNcode);
		twBasWorkOrder.setStatus("CREATED");
		twBasWorkOrder.setMarkStatus(0);
		twBasWorkOrderService.insertTwBasWorkOrder(twBasWorkOrder);
	}

	@Override
	public ResultBean updatePlanCreate(Map<String, Object> map) {
		ResultBean resultBean = new ResultBean(true, "'");
		String templateId = (String) map.get("templateId");
		@SuppressWarnings("unchecked")
		List<Map<String,Object>> list = (List<Map<String,Object>>) map.get("params");
		ArrayList<Integer> list2 = new ArrayList<Integer>();
		for (Map<String,Object> map2 : list) {
			list2.add((Integer)map2.get("id"));
		}
		List<InfPpPlan> selectDateListById = twProductionPlanMapper.selectDateListById(list2);
		if (templateId != null && list.size() != 0) {
			twProductionPlanMapper.updateSortNum(list);
			if (templateId.equals("905")) {
				twProductionPlanMapper.updateSort(list);
			} else if (templateId.equals("909")) {
				twProductionPlanMapper.updatePlanAdjust(list);
			} else if (templateId.equals("915")) {
				twProductionPlanMapper.updateplanApproval(list);
			} else if (templateId.equals("917-freeze")) {
				// 当mes_plan_schedule_info 排产表存在数据时批量删除数据
				twProductionPlanMapper.deleteMesPlanScheduleInfoMap(list);
				// 计划冻结
				twProductionPlanMapper.updatePlanFreeze(list);
			} else if (templateId.equals("921")) {
				twProductionPlanMapper.updatePlanReview(list);
			} else if (templateId.equals("917-sent")) {
				twProductionPlanMapper.updatePlanSent(list);
			} else if (templateId.equals("919")) {
				boolean flag=true;
				for (InfPpPlan infPpPlan : selectDateListById) {
					if (!infPpPlan.getPlanStatus().equals("70")) {
						flag = false;
					}
				}
				if (flag) {
					twProductionPlanMapper.updateUnfreeze(selectDateListById);
				} else {
					resultBean.setSuccess(false);
					resultBean.message = "未冻结的订单无法解冻！";
				}
			} else if (templateId.equals("refuse")) {
				// 当mes_plan_schedule_info 排产表存在数据时批量删除数据
				twProductionPlanMapper.deleteMesPlanScheduleInfoMap(list);
				
				twProductionPlanMapper.updateRefuse(list);
			} else {
				resultBean.setSuccess(false);
				resultBean.message = "选择错误";
			}
		} else {
			resultBean.setSuccess(false);
			resultBean.message = "无法查询到所选项";
		}
		return resultBean;

	}

	@Override
	public void deletePlanCreate(Map<String, Object> map) {
		ResultBean resultBean = new ResultBean(true, "'");
		@SuppressWarnings("unchecked")
		List<InfPpPlan> list = (List<InfPpPlan>) map.get("params");
		if (list != null && list.size() != 0) {
			// 当mes_plan_schedule_info 排产表存在数据时批量删除数据
			twProductionPlanMapper.deleteMesPlanScheduleInfo(list);
			// 批量删除计划表数据
			twProductionPlanMapper.deletePlanCreate(list);
		} else {
			resultBean.setSuccess(false);
			resultBean.message = "删除失败";
		}
	}

	@Override
	public ResultBean PlanSort(Map<java.lang.String, Object> map) {
		ResultBean resultBean = new ResultBean(true,"'");
		String sortButton = (String)map.get("sortButton");
		if (sortButton!=""&&sortButton.equals("up")) {
			@SuppressWarnings("unchecked")
			List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("params");
			if (list.size()!=1) {
				resultBean.setSuccess(false);
				resultBean.setMessage("请只选择一条数据！");
			} else {
				Map<java.lang.String, Object> map2 = list.get(0);
				Integer id = (Integer)map2.get("id");
				InfPpPlan selectDateById = twProductionPlanMapper.selectDateById(id);
				String planOnlineDate = (String)map2.get("planOnlineDate");
				List<Integer> nums = twProductionPlanMapper.selectSortNumByPlanOnlineDate(planOnlineDate);
				if (nums.size() == 0) {
					resultBean.setSuccess(false);
					resultBean.setMessage("无法查询出记录！");
					return resultBean;
				}
				Collections.sort(nums);
//				Integer sortNum = (Integer)map2.get("sortNum");
				Integer sortNum = selectDateById.getSortNum();
				Integer indexOf = nums.indexOf(sortNum);
				if (indexOf==0) {
					resultBean.setSuccess(false);
					resultBean.setMessage("此数据已是本日期第一条数据！");
				}else {
					Integer Num = nums.get(indexOf-1);
					Integer selectIdBySortNum = twProductionPlanMapper.selectIdBySortNum(Num);
					Map<String,Integer> sortInfo=new HashMap<String,Integer>();
					sortInfo.put("currentChangeBeforeId", (Integer)map2.get("id"));
					sortInfo.put("currentChangeAfterId", Num);
					sortInfo.put("sortChangeBeforeId", selectIdBySortNum);
					sortInfo.put("sortChangeAfterId", sortNum);
					twProductionPlanMapper.sortUpdateId(sortInfo);
				}
			}
			
		} else if (sortButton!=""&&sortButton.equals("down")) {
			List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("params");
			if (list.size()!=1) {
				resultBean.setSuccess(false);
				resultBean.setMessage("请只选择一条数据！");
			} else {
				Map<java.lang.String, Object> map2 = list.get(0);
				String planOnlineDate = (String)map2.get("planOnlineDate");
				Integer id = (Integer)map2.get("id");
				InfPpPlan selectDateById = twProductionPlanMapper.selectDateById(id);
				List<Integer> nums = twProductionPlanMapper.selectSortNumByPlanOnlineDate(planOnlineDate);
				Collections.sort(nums);
				Integer indexOf = nums.indexOf(selectDateById.getSortNum());
				if (indexOf == nums.size()-1) {
					resultBean.setSuccess(false);
					resultBean.setMessage("此数据已是本日期最后一条数据！");
				}else {
					Integer Num = nums.get(indexOf+1);
					Integer selectIdBySortNum = twProductionPlanMapper.selectIdBySortNum(Num);
					Map<String,Integer> sortInfo=new HashMap<String,Integer>();
					sortInfo.put("currentChangeBeforeId", (Integer)map2.get("id"));
					sortInfo.put("currentChangeAfterId", Num);
					sortInfo.put("sortChangeBeforeId", selectIdBySortNum);
					sortInfo.put("sortChangeAfterId", selectDateById.getSortNum());
					twProductionPlanMapper.sortUpdateId(sortInfo);
				}
			}
		} else {
			resultBean.setSuccess(false);
		}
		return resultBean;
		
	}

	@Override
	public ResultBean insertPlanCreate(InfPpPlan infPpPlan) {
		ResultBean resultBean = new ResultBean();
		// 校验计划订单号唯一性
		List<Integer> ids = twProductionPlanMapper.selectInfoPpPlanColUni(new InfPpPlan(infPpPlan.getPlanOrderNo()));
		if (ids.size()>0) {
			resultBean.setSuccess(false);
			resultBean.setMessage("计划订单号必须唯一!");
		} else {
			resultBean.setSuccess(true);
			infPpPlan.setCompanyCode(SpringWebUtils.getRequestCompany());
			if(infPpPlan.getCreateTime()==null) {
				infPpPlan.setCreateTime(new Date());
				infPpPlan.setCreateUser(SpringWebUtils.getRequestUser());
				infPpPlan.setLastUpdateTime(new Date());
				infPpPlan.setLastUpdateUser(SpringWebUtils.getRequestUser());
			} else {
				infPpPlan.setLastUpdateTime(new Date());
				infPpPlan.setLastUpdateUser(SpringWebUtils.getRequestUser());
			}
			twProductionPlanMapper.planInsertCreate(infPpPlan);
			twProductionPlanMapper.updatePlanCreationSortNum(infPpPlan.getId());
		}
		return resultBean;
	}

}
